﻿using System.Windows;
using System.Windows.Controls;
using SABnzbdNET.Dialogs;

namespace SABnzbdNET.Views
{
    /// <summary>
    /// Interaction logic for Settings.xaml
    /// </summary>
    public partial class Settings : UserControl
    {
        public Settings()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            SaveSettings();
            ((Main)Application.Current.MainWindow).UpdateServerStatus();
            Application.Current.Windows[1].Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Windows[1].Close();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            txtPassword.Password = Properties.Settings.Default.ServerPassword;
            chkStartup.IsChecked = GetStartup("SABnzbdNET");
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.ServerPassword = txtPassword.Password;
            Properties.Settings.Default.Save();
            SetStartup("SABnzbdNET", chkStartup.IsChecked == true);
        }

        private void SetStartup(string AppName, bool enable)
        {
            string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

            Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKey);

            if (enable)
            {
                if (startupKey.GetValue(AppName) == null)
                {
                    startupKey.Close();
                    startupKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKey, true);
                    startupKey.SetValue(AppName, System.Reflection.Assembly.GetExecutingAssembly().Location);
                    startupKey.Close();
                }
            }
            else
            {
                startupKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKey, true);
                startupKey.DeleteValue(AppName, false);
                startupKey.Close();
            }
        }

        private bool GetStartup(string AppName)
        {
            string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
            Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKey);
            return startupKey.GetValue(AppName) != null;
        }
    }
}
